<template>
  <div class="background">
    <transition name="fade">
    <div class="forgot-password-wrapper">
      <div class="forgot-password-card">
        <h1 class="form-title">重置密码</h1>
        <el-form ref="forgotForm" :model="forgotForm" :rules="rules" class="forgot-form" autocomplete="off">
          <!-- 邮箱 -->
          <el-form-item prop="email">
            <el-input
                v-model="forgotForm.email"
                placeholder="请输入邮箱/手机号"
                prefix-icon="el-icon-message"
                autocomplete="off"
            />
          </el-form-item>
          <!-- 验证码 -->
          <el-form-item prop="verificationCode">
            <div class="verification-container">
              <el-input
                  v-model="forgotForm.verificationCode"
                  placeholder="请输入验证码"
                  prefix-icon="el-icon-key"
                  autocomplete="off"
              />
              <el-button
                  type="primary"
                  class="send-code-button"
                  :disabled="isSending"
                  @click="sendVerificationCode"
              >
                {{ buttonLabel }}
              </el-button>
            </div>
          </el-form-item>
          <!-- 新密码 -->
          <el-form-item prop="newPassword">
            <div class="password-input-wrapper">
            <el-input
                v-model="forgotForm.newPassword"
                placeholder="请输入新密码，密码至少为8位，包含大小写字母和数字"
                :type="passwordVisible_one ? 'text' : 'password'"
                prefix-icon="el-icon-lock"
                autocomplete="new-password"
            />
            <button
                type="button"
                class="toggle-password-button"
                @click="togglePasswordVisibility_one"
            >
              <i :class="passwordVisible_one ? 'el-icon-view' : 'el-icon-view-off'"></i>
            </button>
              </div>
          </el-form-item>
          <!-- 确认新密码 -->
          <el-form-item prop="confirmPassword">
            <div class="password-input-wrapper">
            <el-input
                v-model="forgotForm.confirmPassword"
                placeholder="请再次输入新密码"
                :type="passwordVisible_two ? 'text' : 'password'"
                prefix-icon="el-icon-lock"
                autocomplete="new-password"
            />
            <button
                type="button"
                class="toggle-password-button"
                @click="togglePasswordVisibility_two"
            >
              <i :class="passwordVisible_two ? 'el-icon-view' : 'el-icon-view-off'"></i>
            </button>
              </div>
          </el-form-item>
          <!-- 确认与取消按钮 -->
          <el-form-item>
            <el-button
                type="primary"
                class="wide-button"
                block
                @click="resetPassword"
            >
              确认
            </el-button>
          </el-form-item>
          <el-form-item>
            <router-link to="/login">
              <el-button type="default" class="wide-button" block>取消</el-button>
            </router-link>
          </el-form-item>
        </el-form>
      </div>
    </div>
    </transition>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "ForgotPasswordView",
  data() {
    return {
      forgotForm: {
        email: "",
        verificationCode: "",
        newPassword: "",
        confirmPassword: "",
      },
      rules: {
        email: [
          {required: true, message: "邮箱/手机号不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
              const phoneRegex = /^[1][3-9][0-9]{9}$/;
              if (!emailRegex.test(value) && !phoneRegex.test(value)) {
                callback(new Error("请输入有效的邮箱或手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        verificationCode: [{required: true, message: "验证码不能为空", trigger: "blur"}],
        newPassword: [{required: true, message: "新密码不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
              if (!passwordPattern.test(value)) {
                callback(new Error("密码至少为8位且包含数字和大小写字母"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
          ],
        confirmPassword: [
          {required: true, message: "请再次输入新密码", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if (value !== this.forgotForm.newPassword) {
                callback(new Error("两次密码输入不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      isSending: false,
      countdown: 0,
      passwordVisible_one: false,
      passwordVisible_two: false
    };
  },
  computed: {
    buttonLabel() {
      return this.isSending ? `${this.countdown}秒后重新发送` : "发送验证码";
    },
  },
  methods: {
    togglePasswordVisibility_one() {
      this.passwordVisible_one = !this.passwordVisible_one;
    },
    togglePasswordVisibility_two() {
      this.passwordVisible_two = !this.passwordVisible_two;
    },
    sendVerificationCode() {
      if (this.forgotForm.email.trim() === "") {
        this.$message.error("请输入邮箱");
        return;
      }
      axios
          .post("http://localhost:8095/user/sendVerificationCode", {
            email: this.forgotForm.email,
          })
          .then((response) => {
            if (response.data.code === 200) {
              this.$message.success("验证码已发送到您的邮箱");
              this.startCountdown();
            } else {
              this.$message.error("发送验证码失败");
            }
          })
          .catch((error) => {
            console.error(error);
            this.$message.error("发送验证码失败");
          });
    },
    startCountdown() {
      this.isSending = true;
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isSending = false;
        }
      }, 1000);
    },
    resetPassword() {
      this.$refs.forgotForm.validate((valid) => {
        if (valid) {
          axios
              .post("http://localhost:8095/user/forgotPassword", this.forgotForm)
              .then((response) => {
                if (response.data.code === 200) {
                  this.$message.success("密码重置成功");
                  this.$router.push({name: "Login"});
                } else {
                  this.$message.error("密码重置失败，验证码无效或已过期");
                }
              })
              .catch((error) => {
                console.error(error);
                this.$message.error("请求失败，请稍后重试");
              });
        }
      });
    },
  },
};
</script>

<style scoped>
/* 主背景 */
.background {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url("@/assets/background/background02.jpeg") no-repeat center center fixed;
  background-size: cover;
}

/* 外框 */
.forgot-password-wrapper {
  background: rgba(255, 255, 255, 0.9);
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 450px; /* 增大框体 */
  max-width: 90%;
  animation: fadeIn 1.2s ease-out; /* 动画 */
}

/* 卡片样式 */
.forgot-password-card {
  text-align: center;
}

/* 表单标题 */
.form-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

/* 验证码输入框与按钮 */
.verification-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 发送验证码按钮 */
.send-code-button {
  white-space: nowrap;
  height: 40px;
}

/* 宽按钮 */
.wide-button {
  width: 100%;
  height: 40px;
}

/* 波纹效果 */
.ripple-effect {
  position: relative;
  overflow: hidden;
}

.ripple-effect::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.7);
  opacity: 0;
  border-radius: 50%;
  transform: translate(-50%, -50%) scale(1);
  animation: ripple 0.6s ease-out;
}

.ripple-effect:active::after {
  animation: ripple 0.6s ease-out;
}

@keyframes ripple {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.7;
  }
  100% {
    transform: translate(-50%, -50%) scale(10);
    opacity: 0;
  }
}

/* 淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 密码输入框容器 */
.password-input-wrapper {
  display: flex;
  align-items: center;
  position: relative;
}

.toggle-password-button {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  color: #888;
}

.toggle-password-button:hover {
  color: #555;
}
</style>
